package com.zyg.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LoginFilter implements Filter {

    
	public void destroy() {
		// TODO Auto-generated method stub
	}

	//登录的拦截，如果用户未登录，不允许访问除登录页面以外的信息
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		//获取访问路劲
		String uri = request.getRequestURI();
		
		//如果当前的访问路劲是登录以外的，拦截下来做session判断
		if(!uri.contains("login")) {
			HttpSession session = request.getSession();
			Object obj = session.getAttribute("username");
			//如果当前session中没有账户信息，返回登录，告诉用户请登录后访问
			if(null == obj) {
				request.setAttribute("error", "请登陆后再访问");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}
		}
		chain.doFilter(request, response);
	}

	
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
